import axios from "axios";
import { message } from "antd";
import { adminToken } from "@/utils/variable";
import NProgress from "nprogress";

let requestTimeOut = 20000;
const request = axios.create({
    baseURL: process.env.REACT_APP_BASEURL,
    timeout: requestTimeOut,
    withCredentials: true
});
let timerLock = false;
let timerInterval = 3000;
const messageLock = () => {
    return new Promise((resolve, reject) => {
        if (!timerLock) {
            timerLock = true;
            setTimeout(() => {
                timerLock = false;
            }, timerInterval);
            resolve();
        } else {
            reject();
        }
    });
};
let progressTimer = null;
let progressInterval = 16;
request.interceptors.request.use(
    config => {
        // Do something before request is sent
        let token = localStorage[adminToken];
        token ? (config.headers.Authorization = `Bearer ${token}`) : false;
        NProgress.done();
        NProgress.start();
        progressTimer ? clearInterval(progressTimer) : false;
        progressTimer = setInterval(() => {
            NProgress.inc((progressInterval - 8) / requestTimeOut);
        }, progressInterval);
        return config;
    },
    error => {
        // Do something with request error
        return Promise.reject(error);
    }
);
request.interceptors.response.use(
    response => {
        // Do something before response is sent
        clearInterval(progressTimer);
        NProgress.done();
        if (response.data.code == 401) {
            messageLock().then(res => {
                message.warn(response.data.message);
                setTimeout(() => {
                    location = "/#/login";
                }, 1500);
            });
        }else if(response.data.code != 200){
            messageLock().then(res => {
                message.warn(response.data.message);
            });
        }
        return response.data;
    },
    error => {
        if (error.response && error.response.data) {
            messageLock().then(() => {
                message.error(error.response.data.message);
            });
        }
        let originalRequest = error.config;
        if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1 && !originalRequest._retry) {
            // eslint-disable-next-line
            message.error("请检查网络再重新连接");
            clearInterval(progressTimer);
            NProgress.done();
            return Promise.reject("请检查网络再重新连接");
        }
        // Do something with response error
        clearInterval(progressTimer);
        NProgress.done();
        return Promise.reject(error);
    }
);

export default request.request;
